﻿using Core.Framework.EntityExtend;
using Core.Framework.Model.Common;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq.Expressions;

namespace Core.Business
{
    public class Utils
    {
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T1">数据库连接对象类型</typeparam>
        /// <typeparam name="T2">实体类型</typeparam>
        /// <param name="model">操作实体</param>
        /// <param name="sqlExecType">操作类型</param>
        /// <param name="where">操作条件</param>
        /// <param name="beforeAction">提交之前插入事件</param>
        /// <param name="afterAction">提交之后插入事件</param>
        /// <returns></returns>
        public static MethodResult<int> SqlExecType<T1, T2>(T2 model, SqlExecType sqlExecType, Expression<Func<T2, bool>> where, Action<T1> beforeAction = null, Action<T1> afterAction = null)
            where T1 : DbContext, new()
            where T2 : class, new()
        {
            try
            {
                using (var context = new T1())
                {

                    if(beforeAction != null)
                        beforeAction.Invoke(context);

                    context.ExecBySqlExecType(
                        model,
                        sqlExecType,
                        where);



                    int row = context.BeginSaveChanges(out string error);

                    if (afterAction != null && row > 0)
                    {
                        afterAction.Invoke(context);
                        context.BeginSaveChanges();
                    }

                    // 如果执行插入操作
                    if (row > 0 & sqlExecType == Framework.Model.Common.SqlExecType.insert)
                    {
                        var type = model.GetType();

                        var property = type.GetProperty("Id");

                        // 则返回 插入的主键
                        row = (int)property.GetValue(model);

                    }

                    return new MethodResult<int>
                    {
                        IsFinished = string.IsNullOrWhiteSpace(error),
                        Date =  row,
                        Discription = error
                    };
                }
            }
            catch (Exception e)
            {
                return new MethodResult<int> { IsFinished = false, Date = 0, Discription = e.Message };
            }
        }
    }
}
